package com.reason.oauth.controller;


import com.reason.common.enums.RedisMessageStatusCode;
import com.reason.common.exception.HWException;
import com.reason.common.pojo.Result;
import com.reason.common.pojo.StatusCode;
import com.reason.common.utils.IdWorker;
import com.reason.oauth.service.AuthService;
import com.reason.oauth.utils.AuthToken;
import com.reason.oauth.utils.CookieUtil;
import com.reason.user.feign.CustomerFeign;
import com.reason.user.pojo.Customer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 授权controller
 */
@Controller
@RequestMapping("/oauth")
public class AuthController {

    /**
     * 客户端id
     */
    @Value("${auth.clientId}")
    private String clientId;

    /**
     * 客户端密钥
     */
    @Value("${auth.clientSecret}")
    private String clientSecret;

    /**
     * service服务注入
     */
    @Autowired
    private AuthService authService;

    /**
     * 获取cookie的域名
     */
    @Value("${auth.cookieDomain}")
    private String cookieDomain;


    /**
     * cookie的有效期，为-1就是关闭浏览器就没有了
     */
    @Value("${auth.cookieMaxAge}")
    private Integer cookieMaxAge;


    /**
     * 注入cusyomer的feign接口
     */
    @Autowired
    private CustomerFeign customerFeign;


    /**
     * 注入redisTemplate
     */
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String DEFAULT_PASSWORD = "helloworld";


    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
//    @RequestMapping("/login")
//    @ResponseBody
//    public Result login(String username, String password, HttpServletResponse response){
//
//        //调用AuthService完成登陆
//        String grant_type="password";
//
//        AuthToken authToken = authService.login(username, password, clientId, clientSecret,grant_type);
//
//        if(authToken!=null){
//            this.setJtiToCookie(authToken.getJti(),response);
//            return new Result(true, StatusCode.OK,"令牌返回成功!!",authToken);
//
//        }
//        return null;
//
//
//    }


    /**
     * 将jwt令牌的短标识存入cookie中
     */
    public void setJtiToCookie(String jti,HttpServletResponse response){
        CookieUtil.addCookie(response,cookieDomain,"/","uid",jti,cookieMaxAge,false);
    }


    /**
     * 跳转登陆
     */
    @RequestMapping("/toLogin")
    public String toLogin(){

        System.out.println("登陆中");
        return "login";
    }




    /**
     * 用户通过电话号码登陆
     * @param
     * @param
     * @return
     */
    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestBody Map<String,Object> map, HttpServletResponse response){

        //获取电话号码并查询
        String telephoneStr = (String) map.get("telephone");
        long telephone = Long.parseLong(telephoneStr);

        //通过手机号获取短信验证码
        String code = stringRedisTemplate.opsForValue().get(telephoneStr + RedisMessageStatusCode.SENDTYPE_REGISTER);
        if(StringUtils.isEmpty(map.get("code"))){
            //如果前端输入验证码为空
            return new Result(false,StatusCode.ERROR,"您输入的验证码为空！！");
        }

        //如果验证码不对
        if(!map.get("code").equals(code)){
            return new Result(false,StatusCode.ERROR,"您输入的验证码不对");
        }else{
            //验证码成功，登陆成功！！
            //第一查询该用户是否注册过
            Customer customer = customerFeign.findByTelephone(telephone);
            if(customer==null){
                customer = new Customer();
                //未登陆过，注册一级用户
                customer.setPhone(telephone);
                //生成id设置
                IdWorker idWorker = new IdWorker(1,1);
                long uid = idWorker.nextId();
                customer.setId(uid);
                //随机生成一个默认的名字you handsome
                customer.setName("HW_" + telephone);
                //随机生成个password设置
                customer.setPassword(DEFAULT_PASSWORD);
                //设置member表示用户的角色
                customer.setMember(0);
                //存入数据库
                customerFeign.register(customer);
            }
            //调用AuthService完成登陆
            String grant_type="password";

            AuthToken authToken;
            try {
                authToken = authService.login(customer.getName(), DEFAULT_PASSWORD, clientId, clientSecret,grant_type);
            } catch (Exception e) {
                return new Result(false, StatusCode.ERROR,"用户名或密码错误！！");
            }

            if(authToken!=null){
//                this.setJtiToCookie(authToken.getJti(),response);
                Integer member = customer.getMember();
                // 返回用户的级别
                Map<String, Object> data = new HashMap<>();
                data.put("status", customer.getMember());
                data.put("uid", authToken.getJti());
                data.put("id", customer.getId().toString());
                data.put("username", customer.getName());
                return new Result(true, StatusCode.OK,"登陆成功！！", data);
            }

            return new Result(false, StatusCode.ERROR,"登陆异常，请稍后重试");

        }



    }

}
